//
//  THManageViewController.swift
//  LaiLang
//
//  Created by David on 2017/2/17.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

class THManageViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    var tableView:UITableView!
    
    var data: NSArray?
    
    var emptyView: UILabel!
    
    var toolbar: UIView!
    
    var postBtn: UIButton!
    var mineBtn: UIButton!
    
    var refreshControl: LLRefreshControl!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let navbar = LLAdaptHideNavBar(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64), title: "我的树洞", navigator: navigationController)
        
        // Do any additional setup after loading the view.
        
        tableView = UITableView(frame: CGRect(x: 0, y: 44, width: view.bounds.width, height: view.bounds.height - 44), style: .grouped)
        view.addSubview(tableView)
        
        
        emptyView = UILabel(frame: CGRect(x: 0, y: 44, width: view.bounds.width, height: 64))
        emptyView.textColor = UIColor.lightGray
        emptyView.textAlignment = .center
        emptyView.font = UIFont.systemFont(ofSize: 14)
        emptyView.text = emptyPlaceholder
        tableView.addSubview(emptyView)
        
        view.addSubview(navbar)
        
//        initToolbar()
        
        refreshControl = LLRefreshControl(frame: CGRect(x: 0, y: -64, width: view.bounds.width, height: 64))
        tableView.addSubview(refreshControl)
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        
        THRefreshList()
        
        
    }
    
    func initToolbar(){
        toolbar = UIView(frame: CGRect(x: -1, y: view.bounds.height - 44, width: view.bounds.width+2, height: 45))
        toolbar.backgroundColor = UIColor.white
        toolbar.layer.borderWidth = 1
        toolbar.layer.borderColor = UIColor.lightGray.cgColor
        view.addSubview(toolbar)
        
        postBtn = UIButton(frame: CGRect(x: 0, y: 0, width: view.bounds.width/2, height: 44))
        postBtn.setTitle("我要表白", for: .normal)
        postBtn.setTitleColor(themeColor, for: .normal)
        postBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        toolbar.addSubview(postBtn)
        postBtn.addTarget(self, action: #selector(THViewController.gotoPost), for: .touchUpInside)
        
        mineBtn = UIButton(frame: CGRect(x: view.bounds.width/2, y: 0, width: view.bounds.width/2, height: 44))
        mineBtn.setTitle("我的树洞", for: .normal)
        mineBtn.setTitleColor(themeColor, for: .normal)
        mineBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        toolbar.addSubview(mineBtn)
        mineBtn.addTarget(self, action: #selector(THViewController.gotoMine), for: .touchUpInside)
        
        let border = UIView(frame: CGRect(x: 0, y: 8, width: 1, height: 32))
        border.center.x = view.bounds.width/2
        border.backgroundColor = UIColor.lightGray
        toolbar.addSubview(border)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if data != nil {
            if data!.count > 0{
                return data!.count
            }
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //        if data != nil {
        //            if data!.count > 0{
        //                let thisData = data?.object(at: indexPath.row) as? NSDictionary
        //                if thisData != nil {
        //                    let thisStr = thisData?.object(forKey: "content") as? String
        //                    if thisStr != nil {
        //
        //                        return (thisStr! as NSString).boundingRect(with: CGSize(width: view.bounds.width - 32, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14)], context: nil).height + 100
        //                    }
        //
        //                }
        //            }
        //        }
        return 256
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0{
            return 0.001
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "item")
        cell.selectionStyle = .none
        cell.backgroundColor = UIColor.clear
        var empty = true
        if data != nil {
            if data!.count > 0{
                empty = false
                
                var toName:String?
                
                //                var toMajorWidth:CGFloat = 0.0
                var toMajorStr:String?
                
                //                var contentHeight:CGFloat = 0.0
                var contentStr:String?
                
                var fromStr = "来自"
                var fromName: String?
                var fromMajor:String?
                
                
                var color:Int?
                
                var likeNum = 0
                var commentNum = 0
                
                let thisData = data?.object(at: indexPath.row) as? NSDictionary
                if thisData != nil {
                    
                    toName = thisData?.object(forKey: "to_name") as? String
                    
                    toMajorStr = thisData?.object(forKey: "to_major") as? String
                    //                    if toMajorStr != nil {
                    //                        toMajorWidth = (toMajorStr! as NSString).boundingRect(with: CGSize(width: view.bounds.width - 40, height: 16), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 10)], context: nil).width
                    //                    }
                    
                    contentStr = thisData?.object(forKey: "content") as? String
                    //                    if contentStr != nil {
                    //                        contentHeight = (contentStr! as NSString).boundingRect(with: CGSize(width: view.bounds.width - 32, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14)], context: nil).height
                    //                    }
                    
                    fromName = thisData?.object(forKey: "from_name") as? String
                    fromMajor = thisData?.object(forKey: "from_major") as? String
                    let postTime = thisData?.object(forKey: "post_time") as? String
                    
                    if fromMajor != nil {
                        fromStr += "\(fromMajor!)的"
                    }
                    
                    if fromName != nil {
                        fromStr += fromName!
                    }else{
                        fromStr += "某某"
                    }
                    
                    if postTime != nil {
                        fromStr += "\n\(postTime!)"
                    }else{
                        fromStr += "神秘时间"
                    }
                    
                    color = thisData?.object(forKey: "color") as? Int
                    
                    likeNum = thisData?.object(forKey: "like") as? Int ?? 0
                    commentNum = thisData?.object(forKey: "comment") as? Int ?? 0
                }
                
                let cardBG = THCardView(frame: CGRect(x: 16, y: 48, width: view.bounds.width - 32, height: 204)) //64-56
                //                cardBG.backgroundColor = UIColor.white
                //                cardBG.layer.cornerRadius = 8
                //                cardBG.layer.masksToBounds = true
                cell.addSubview(cardBG)
                
                
                //                let avatarImgBtn = UIButton(frame: CGRect(x: 8, y: 6, width: 40, height: 40))
                //                avatarImgBtn.backgroundColor = UIColor.lightGray
                //                avatarImgBtn.layer.cornerRadius = 20
                //                cardBG.addSubview(avatarImgBtn)
                //
                //                let fromNameLabel = UILabel(frame: CGRect(x: 56, y: 6, width: view.bounds.width - 32 - 72 - 80, height: 20))
                //                fromNameLabel.font = UIFont.systemFont(ofSize: 14)
                //                cardBG.addSubview(fromNameLabel)
                //
                //                let fromMajorLabel = LLRoundRectLabel(frame: CGRect(x: 56, y: 28, width: 200, height: 16))
                //                fromMajorLabel.font = UIFont.systemFont(ofSize: 10)
                //                fromMajorLabel.textColor = themeColor
                //                cardBG.addSubview(fromMajorLabel)
                
                
                
                var contentFullStr = ""
                var toNameLength = 0
                if toName != nil {
                    contentFullStr += "\(toName!):\n\n\n"
                    toNameLength = toName!.characters.count
                }
                var contentStrLength = 0
                if contentStr != nil {
                    contentFullStr += "　　\(contentStr!)"
                    contentStrLength = contentStr!.characters.count
                }
                
                let attrStr = NSMutableAttributedString(string: contentFullStr)
                attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 16), range: NSMakeRange(0, toNameLength))
                attrStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(toNameLength + 6, contentStrLength))
                attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.white, range: NSMakeRange(0, contentFullStr.characters.count))
                cardBG.fullContent = attrStr
                //                contentLabel.attributedText = attrStr
                //                contentLabel.sizeToFit()
                
                cardBG.toMajor = toMajorStr
                //                toMajorTag.text = toMajorStr
                
                //                fromNameLabel.text = fromName
                //                fromMajorLabel.text = fromMajor
                //                rightLabel.text = fromStr
                cardBG.bottomContent = fromStr
                
                if color != nil {
                    cardBG.bgColor = LLColor.getColorFromTable(by: color!)
                    //                    contentBG.backgroundColor = LLColor.getColorFromTable(by: color!)
                }
                
                
                
                
                cardBG.likeNum = likeNum
                cardBG.likeBtn.tag = indexPath.row
                cardBG.likeBtn.addTarget(self, action: #selector(THViewController.hitLikeBtn(sender:)), for: .touchUpInside)
                
                
                
                cardBG.commentNum = commentNum
                cardBG.commentBtn.tag = indexPath.row
                cardBG.commentBtn.addTarget(self, action: #selector(THViewController.gotoComment(sender:)), for: .touchUpInside)
            }
        }
        if empty {
            cell.addSubview(emptyView)
        }
        return cell
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y < -96 {
            if refreshControl.state == .Normal {
                refreshControl.readyToRefresh()
            }
        }else{
            if refreshControl.state == .Ready{
                refreshControl.endRefresh()
            }
        }
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if refreshControl.state == .Ready {
            THRefreshList()
            
        }
    }
    
    func THRefreshList(){
        print("表白墙刷新列表")
        refreshControl.beginRefresh()
        var insert = tableView.contentInset
        insert.top += 64
        tableView.contentInset = insert
        
        
        //TODO: 表白墙获取列表
        
        
        
        if #available(iOS 10.0, *) {
            Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { (timer) in
                self.refreshControl.endRefresh()
                
                var insert = self.tableView.contentInset
                insert.top -= 64
                self.tableView.contentInset = insert
                //                self.tableView.setContentOffset(CGPoint(x: 0, y: -20), animated: true)
                //西安大程冶金装备有限公司专业从事铁合金矿热炉及炼 钢电弧炉、精炼炉装备研发、设计、生产、安装调试服务的 高新技术企业。
                self.data = [
                    [
                        "to_name":"张三",
                        "to_major":"工商管理系",
                        "from_name":"李四",
                        "from_major":"中文系",
                        "post_time":"2016-02-01 11:34:53",
                        "content": "哈哈",
                        "color": 1,
                        "like": 2,
                        "comment": 3
                    ],
                    [
                        "to_name":"啊啊啊啊啊啊啊啊",
                        "to_major":"计算机科学与技术系",
                        "from_name":"哦哦哦哦哦哦哦哦",
                        "from_major":"国际贸易与金融系",
                        "post_time":"2016-01-28 11:34:53",
                        "content": "公司始终以科技创新为主导,以创造客户价值为己任。 实践中强调先进性与实用性相结合,追求稳定可靠。 公司汇聚了一批科研技术人员,包括在电炉行业当中有 较高声誉的专家学者。近年来紧跟行业技术进步步伐,围绕 国家产业政策不断升级的市场要求,开拓创新,锻炼出一支 年富力强的专业技术队伍。",
                        "color": 2,
                        "like": 0,
                        "comment": 0
                    ]
                    ] as NSArray
                
                self.tableView.reloadData()
                
                var empty = true
                if self.data != nil {
                    if self.data!.count > 0{
                        self.emptyView.alpha = 0
                        empty = false
                    }
                }
                if empty {
                    self.emptyView.alpha = 1
                }
            }
        } else {
            
        }
    }
    
    func THGetList(page: Int){
        print("翻页列表获取")
        //TODO: 表白墙获取列表
    }
    
//    func gotoPost(){
//        hidesBottomBarWhenPushed = true
//        navigationController?.pushViewController(THPostViewController(), animated: true)
//    }
//    
//    func gotoMine(){
//        hidesBottomBarWhenPushed = true
//        navigationController?.pushViewController(THManageViewController(), animated: true)
//    }
    
    func hitLikeBtn(sender: UIButton){
        print("like \(sender.tag)")
    }
    
    func gotoComment(sender: UIButton){
        print("going to \(sender.tag) comment")
        let thisData = data?.object(at: sender.tag) as? NSDictionary
        if thisData != nil{
            hidesBottomBarWhenPushed = true
            navigationController?.pushViewController(THCommentViewController(dataModal: thisData!), animated: true)
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
